﻿using AutoMapper;
using KWT.DRG_DIP.DB;
using KWT.DRG_DIP.DO.Group.DIPGroup;
using KWT.DRG_DIP.DTO.Group;
using KWT.DRG_DIP.ISvc;
using KWT.DRG_DIP.PO.Basic;

namespace KWT.DRG_DIP.Svc.Group.DIPGroup
{
    public class DipGrouperSvc : IDipGrouperSvc
    {
        public IPolicyEnumSvc policyEnumSvc { get; set; }

        public IMapper _mapper { get; set; }
        public EFContext ef { get; set; }
        public OutGroupResult GetGroupInfo(OutGroupResult? groupResult, string tenantID)
        {
            if (groupResult == null)
                return groupResult;
            var para = ef.Set<Sys_DIP_Para>().SingleOrDefault(x => x.Disease_Code == groupResult.strResult);
            groupResult.strResultName = para == null ? "" : para.Disease_Name;
            if (groupResult?.dIP_Assist != null)
            {
                //查找对应的辅助目录关系
                var standardAssist = ef.Set<Sys_PolicyEnum>().FirstOrDefault(a => a.Group == "辅助目录关系"
                && a.Name3 == groupResult.dIP_Assist.Type && a.Code2 == groupResult.dIP_Assist.Code);
                if (standardAssist == null)
                {
                    throw new Exception($"缺辅助目录关系未能对应上{groupResult.dIP_Assist.Type},{groupResult.dIP_Assist.Code}");
                }
;
                groupResult.dIP_Assist.Code = standardAssist.Code1;
                groupResult.dIP_Assist.Name = standardAssist.Name1;
            }
            return groupResult;
        }

        /// <summary>
        /// 获得病种信息
        /// </summary>
        /// <param name="inputPara">分组参数</param>
        /// <param name="version">分组器版本</param>
        /// <returns></returns>
        public OutGroupResult GroupExecue(InGroupPara inGroupPara, string tenantID)
        {
            var inputPara = _mapper.Map<DIPGroupInputPara>(inGroupPara);

            DIPGroupBase dIPGroupBase = new DIPGroupBase();
            switch (inputPara.version)
            {
                default:
                    dIPGroupBase = new DIPGroup();
                    break;
            }

            #region 初始化规则字典
            //初始化规则字典
            dIPGroupBase.dIP_Rule_DiseaseGroups = policyEnumSvc.GetDiseaseGroup(tenantID);
            dIPGroupBase.dIP_Operation_Info = policyEnumSvc.GetOperInfo(tenantID);
            dIPGroupBase.dIP_Rules = policyEnumSvc.GetDIPRules(tenantID);      
            dIPGroupBase.dIP_Assists = policyEnumSvc.GetDIPAssists(tenantID);
            #endregion

            var result = dIPGroupBase.GroupExecue(inputPara);
            return _mapper.Map<OutGroupResult>(result);
        }
    }
}
